<?php 

/**
* PHP Socket操作类
* @author Hdb <hdb@boyuntong.com>
*/
class BSocket
{
	protected $host;
	protected $port;
	public $socket;
	function __construct($host, $port)
	{
		$this->host = $host;
		$this->port = $port;
		$this->socket = stream_socket_client("tcp://".$this->host.":".$this->port, $err_no, $err_msg);
		if (empty($this->socket)) {
			throw new Exception($err_msg, 1);
		}
		stream_set_blocking($this->socket, true);
	}

	/**
	 * 发送十六进制数据
	 * @param  [type] $hexString 十六进制字符串
	 * @param  string $split     分隔符
	 * @return [type]            [description]
	 */
	public function sendHex($hexString, $split=':')
	{
		$hexArr = explode($split, $hexString);
		foreach ($hexArr as $value) {
			stream_socket_sendto($this->socket, chr(hexdec($value)));
		}
	}

	public function SingleDecToHex($dec)
	{
		$tmp="";
		$dec=$dec%16;
		if($dec<10)
			return $tmp.$dec;
		$arr=array("a","b","c","d","e","f");
		return $tmp.$arr[$dec-10];
	}


	public function SingleHexToDec($hex)
	{
		$v=ord($hex);
		if(47<$v&$v<58)
			return $v-48;
		if(96<$v&$v<103)
			return $v-87;
	}

	public function SetToHexString($str)
	{
		if(!$str)return false;
		$tmp="";
		for($i=0;$i<strlen($str);$i++)
		{
		   $ord=ord($str[$i]);
		   $tmp.=$this->SingleDecToHex(($ord-$ord%16)/16);
		   $tmp.=$this->SingleDecToHex($ord%16);
		}
		return $tmp;
	}


	public function UnsetFromHexString($str)
	{
		if(!$str)return false;
		$tmp="";
		for($i=0;$i<strlen($str);$i+=2)
		{
		   $tmp.=chr($this->SingleHexToDec(substr($str,$i,1))*16+$this->SingleHexToDec(substr($str,$i+1,1)));
		}
		return $tmp;
	}

	/**
	 * 发送字符串
	 * @param  string $value 字符串
	 * @return [type]        [description]
	 */
	public function sendString($value='')
	{
		stream_socket_sendto($this->socket, $value);
	}

	/**
	 * 获取服务器返回数据
	 * @return [type] [description]
	 */
	public function getResponse()
	{
		return stream_socket_recvfrom($this->socket, 65535);
	}

	/**
	 * 关闭socket连接
	 * @return [type] [description]
	 */
	public function close()
	{
		return fclose($this->socket);
	}
}

 ?>